package com.mazaiting.common.core.factory;

import com.mazaiting.common.core.utils.StringUtil;

import javax.validation.constraints.NotNull;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义名称的线程工程
 */
public class NamedThreadFactory implements ThreadFactory {
    /**
     * 线程池数量
     */
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    /**
     * 线程组
     */
    private final ThreadGroup group;
    /**
     * 线程数
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    /**
     * 名字前缀
     */
    private final String namePrefix;

    public NamedThreadFactory(String name) {
        @SuppressWarnings("removal")
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        if (StringUtil.isEmpty(name)) {
            name = "pool";
        }
        namePrefix = name + "-" +
                poolNumber.getAndIncrement() +
                "-thread-";
    }

    /**
     * 创建新线程
     * @param r a runnable to be executed by new thread instance
     * @return 线程
     */
    @Override
    public Thread newThread(@NotNull Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }

    public String getNamePrefix() {
        return namePrefix;
    }
}
